Skip to main content

Coding3 - πŸ“˜ Connecting to MongoDB

🧠 What You’ll Learn​

In this lesson, you’ll:

  • Set up MongoDB for your project
  • Create a reusable connection file using Mongoose
  • Load the connection string from the .env file

βœ… Step 1: Install Mongoose​

In your terminal, run:

npm install mongoose
npm install --save-dev @types/mongoose

βœ… Step 2: Add Your MongoDB URI to .env​

Update your .env file:

SERVER_PORT=5000
MONGODB_URI=mongodb://localhost:27017/my-api

πŸ’‘ Replace my-api with your preferred database name.


βœ… Step 3: Create MongoDB Connection File​

File: src/dbconnect.ts

import mongoose from "mongoose";

const connectDB = async (mongoURI: string) => {
try {
await mongoose.connect(mongoURI);
console.log('βœ… MongoDB Connected: ', mongoURI);
} catch (error) {
console.error('❌ MongoDB connection failed:', error);
process.exit(1); // exit app if connection fails
}
}

export default connectDB;

βœ… This file handles the connection to your MongoDB database and shows a helpful log message.


βœ… Step 4: Use connectDB() in app.ts​

Update your src/app.ts to use the connection:

import 'dotenv/config';
import express from 'express';
import connectDB from './dbconnect';

const app = express();
const PORT = process.env.SERVER_PORT || 5000;

// 🧠 Connect to MongoDB
connectDB(process.env.MONGODB_URI || '');

// Middleware
app.use(express.json());

// Test Route
app.get('/health', (_req, res) => {
res.json({ message: 'Ok' });
});

// Start Server
app.listen(PORT, () => {
console.log(`πŸš€ Server running at http://localhost:${PORT}`);
});

πŸ§ͺ Step 5: Run and Verify​

Run your project:

npm start

βœ… You should see something like:

βœ… MongoDB Connected:  mongodb://localhost:27017/my-api
πŸš€ Server running at http://localhost:5000

πŸ“¦ Folder Structure So Far​

REST-API/
β”œβ”€β”€ src/
β”‚ β”œβ”€β”€ app.ts
β”‚ └── dbconnect.ts
β”œβ”€β”€ .env
β”œβ”€β”€ nodemon.json
β”œβ”€β”€ package.json
β”œβ”€β”€ tsconfig.json

βœ… What’s Next?​

In Lesson 4, you’ll create your User model and build a user authentication system using signup, login, and logout routes.